//
//  MKAlertViewController.swift
//  MKAlert
//
//  Created by 劢克科技 on 2019/5/16.
//  Copyright © 2019 meckey. All rights reserved.
//

import UIKit
import SnapKit

protocol MKAlertViewControllerDelegate {
    func handleDismiss(atIndex: Int)
}

class MKAlertViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        addActions()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    @objc fileprivate func handleClick(button: UIButton) {
        for (key, sub) in containerView.subviews.enumerated() {
            if sub == button {
                self.endAnimation(atIndex: key - 2)
            }
        }
    }
    
    fileprivate func addActions() {
        for (key, action) in actions.enumerated() {
            let actionButton = UIButton(type: .system)
            actionButton.setTitle(action.title, for: .normal)
            actionButton.setTitleColor(#colorLiteral(red: 0.004461955279, green: 0.4793428183, blue: 0.9990835786, alpha: 1), for: .normal)
            actionButton.addTarget(self, action: #selector(handleClick(button:)), for: .touchUpInside)
            
            containerView.addSubview(actionButton)
            actionButton.snp.makeConstraints { (make) in
                make.left.equalTo(containerView.snp_left)
                make.right.equalTo(containerView.snp_right)
                make.height.equalTo(50)
                if key == 0 {
                    make.top.equalTo(descLabel.snp_bottom).offset(16)
                } else if key > 0 && key < actions.count - 1 {
                    guard let last = self.lastButton else { return }
                    make.top.equalTo(last.snp_bottom)
                } else {
                    guard let last = self.lastButton else { return }
                    make.top.equalTo(last.snp_bottom)
                    make.bottom.equalTo(containerView.snp_bottom)
                }
            }
            
            let line = UIView()
            line.backgroundColor = #colorLiteral(red: 0.06562722395, green: 0.1210046562, blue: 0.2446364961, alpha: 0.2965173856)
            line.alpha = 0.2
            actionButton.addSubview(line)
            line.snp.makeConstraints { (make) in
                make.left.equalTo(actionButton.snp_left)
                make.right.equalTo(actionButton.snp_right)
                make.top.equalTo(actionButton.snp_top)
                make.height.equalTo(1)
            }
            
            lastButton = actionButton
        }
    }
    

    //MARK: - Setter
    
    fileprivate var navTitle = ""
    fileprivate var navDesc = ""
    fileprivate var actions = [MKAlertAction]()
    fileprivate var lastButton: UIButton?
    
    init(title: String, desc: String) {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .custom
        self.navTitle = title
        self.navDesc = desc
        
        titleLabel.text = title
        descLabel.text = desc
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addAction(action: MKAlertAction) {
        actions.append(action)
    }
    
    //MARK: - Getter
    var delegate: MKAlertViewControllerDelegate?
    lazy var cover: UIView = {
        let cover = UIView()
        cover.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.2065636004)
        cover.alpha = 0
        cover.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: #selector(handleClose))
        cover.addGestureRecognizer(gesture)
        return cover
    }()
    
    lazy var containerView: UIView = {
        let view = UIView()
        view.alpha = 0
        view.backgroundColor = #colorLiteral(red: 0.9646012187, green: 0.9647662044, blue: 0.9645908475, alpha: 1)
        view.layer.cornerRadius = 20
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 18)
        label.numberOfLines = 0
        label.textAlignment = .center
        return label
    }()
    
    lazy var descLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.numberOfLines = 0
        label.textAlignment = .center
        return label
    }()
    
    //MARK: - Events
    
    @objc fileprivate func handleClose() {
        UIView.animate(withDuration: 0.25, animations: {
            self.cover.alpha = 0
            self.containerView.alpha = 0
        }) { (_) in
            self.dismiss(animated: false, completion: nil)
        }
    }
    
    fileprivate func startAnimation() {
        cover.alpha = 0
        containerView.alpha = 0
        
        UIView.animate(withDuration: 0.25) {
            self.cover.alpha = 1
            self.containerView.alpha = 1
        }
    }
    
    fileprivate func endAnimation(atIndex: Int) {
        UIView.animate(withDuration: 0.25, animations: {
            self.cover.alpha = 0
            self.containerView.alpha = 0
        }) { (_) in
            self.dismiss(animated: false, completion: {
                self.delegate?.handleDismiss(atIndex: atIndex)
            })
        }
    }
}

//MARK: - UI

extension MKAlertViewController {
    fileprivate func setupUI() {
        addSubs()
        layoutSubs()
    }
    
    fileprivate func addSubs() {
        view.addSubview(cover)
        view.addSubview(containerView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(descLabel)
    }
    
    fileprivate func layoutSubs() {
        cover.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(view.snp_top)
            make.bottom.equalTo(view.snp_bottom)
        }
        
        containerView.snp.makeConstraints { (make) in
            make.center.equalTo(view.snp_center)
            make.width.equalTo(view.snp_width).offset(-80)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(containerView.snp_centerX)
            make.width.equalTo(containerView.snp_width).offset(-32)
            make.top.equalTo(containerView.snp_top).offset(16)
        }
        
        descLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(containerView.snp_centerX)
            make.width.equalTo(containerView.snp_width).offset(-32)
            make.top.equalTo(titleLabel.snp_bottom)
        }
    }
}
